//
//  KKFacebookManager.m
//  LoginTest
//
//  Created by kievkao on 5/17/14.
//  Copyright (c) 2014 kievkao. All rights reserved.
//

#import "KKFacebookManager.h"
#import "WebFormHandler.h"

@implementation KKFacebookManager

- (void)loginWithCompletion:(KKCompleteBlock)completion
{
    [[WebFormHandler sharedInstance] setWebFormType:0];
    
    FBAccessTokenData *tokenData = [[FBSession activeSession] accessTokenData];
    
    if (FBSession.activeSession.state == FBSessionStateOpen || FBSession.activeSession.state == FBSessionStateOpenTokenExtended) {
        FBAccessTokenData *tokenData = [[FBSession activeSession] accessTokenData];
        
    } else {
        [FBSession openActiveSessionWithReadPermissions:self.permissions allowLoginUI:YES completionHandler:^(FBSession *session, FBSessionState state, NSError *error) {
            if(FBSession.activeSession.isOpen){
                [[FBRequest requestForMe] startWithCompletionHandler:^(FBRequestConnection *connection, NSDictionary<FBGraphUser> *user, NSError *error) {
                    
                    NSMutableDictionary *userData;
                    
                    if (!error) {
                        userData = [NSMutableDictionary dictionary];
                        
                        [user enumerateKeysAndObjectsUsingBlock:^(id key, id obj, BOOL *stop) {
                            [userData setObject:obj forKey:key];
                        }];
                        
                        self.token = [[[FBSession activeSession] accessTokenData] description];
                    }
                    
                    if (completion) {
                        completion(error, userData);
                    }
                }];
            }
        }];
    }
}

@end
